package com.gosuncn.utils;

import com.aspose.words.ConvertUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpHelperUtil {
    private static Logger logger = LoggerFactory.getLogger(IpHelperUtil.class);
    private final static char[] HEX = "0123456789ABCDEF".toCharArray();

    // private static String[] cardNameHeads = new String[] { "em*", "en0", "en1", "en2", "en3",
    // "en4", "en5", "en6",
    // "en7", "en8", "en9", "eno0", "eno1", "eno2", "eno3", "eno4", "eno5", "eno6", "eno7", "eno8",
    // "eno9", "enp0",
    // "enp1", "enp2", "enp3", "enp4", "enp5", "enp6", "enp7", "enp8", "enp9", "eth0", "eth1",
    // "eth2", "eth3",
    // "eth4", "eth5", "eth6", "eth7", "eth8", "eth9", "eth10", "eth11", "eth12", "eth13", "ens0",
    // "ens1", "ens2",
    // "ens3", "ens4", "ens5", "ens6", "ens7", "ens8", "ens9", "docker0", "docker1", "docker2",
    // "docker3",
    // "docker4", "docker5", "docker6", "docker7", "docker8", "docker9", "lo0", "lo1", "lo2", "lo3",
    // "lo4", "lo5",
    // "lo6", "lo7", "lo8", "lo9", "p8p1", "wlp1s0" };

    /**
     * 匹配网卡名称为：
     * 
     * "em1", "en0", "en1", "en2", "en3", "en4", "en5", "en6",
            "en7", "en8", "en9", "eno0", "eno1", "eno2", "eno3", "eno4", "eno5", "eno6", "eno7", "eno8", "eno9", "enp0",
            "enp1", "enp2", "enp3", "enp4", "enp5", "enp6", "enp7", "enp8", "enp9", "eth0", "eth1", "eth2", "eth3",
            "eth4", "eth5", "eth6", "eth7", "eth8", "eth9", "eth10", "eth11", "eth12", "eth13", "ens0", "ens1", "ens2",
            "ens3", "ens4", "ens5", "ens6", "ens7", "ens8", "ens9", "docker0", "docker1", "docker2", "docker3",
            "docker4", "docker5", "docker6", "docker7", "docker8", "docker9", "lo0", "lo1", "lo2", "lo3", "lo4", "lo5",
            "lo6", "lo7", "lo8", "lo9", "p8p1", "wlp1s0" 
     */
    private final static String[] cardNameHeads = new String[] { "em%s", "eno%s", "enp%s", "eth%s", "ens%s", "docker%s",
            "lo%s", "p8p%s", "wlp1s%s", "en%s" };

    private final static Map<String, String> ips = new HashMap<>();
    private final static Map<String, String> macs = new HashMap<>();

    public static String requestOrigin = null;

    public final static Map<String, String> SERVER_ENV = System.getenv();
    public final static Properties SERVER_PRO = System.getProperties();


    /**
     * @return 本机IP
     * @throws SocketException
     */
    public static String getRealIp() {
        String localip = "::::";// 本地IP，如果没有配置外网IP则返回它
        String netip = "::::";// 外网IP
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            logger.error("获取本机IP出现异常", e);
        }
        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces != null && netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress()
                        .indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }

        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }



    /**
     * <b>@Author </b>robin<br/>
     *
     * @param osname
     * @return
     */
    public static boolean isLinux(String osname) {
        return "Linux".equalsIgnoreCase(osname);
    }

    public static boolean isWindows(String osname) {
        return "Windows".equalsIgnoreCase(osname);
    }

    public static boolean isMac(String osname) {
        return "Mac".equalsIgnoreCase(osname);
    }

    /**
     * 获取FTP的配置操作系统
     * 
     * @return
     */
    public static String getSystemOSName() {
        String sysName = "Windows";
        // 操作系统名称
        String osname = SERVER_PRO.getProperty("os.name");
        if (StringUtils.isNotBlank(osname)) {
            osname = osname.replaceAll("[ ]", "");
            /*
             * if (osname.indexOf("Windows") != -1) { sysName = "Windows"; } else
             */
            if (osname.indexOf("Linux") != -1) {
                sysName = "Linux";
            }
            if (osname.indexOf("Mac") != -1) {
                sysName = "Mac";
            }
        }
        logger.info("当前系统类型[{}]", sysName);
        return sysName;
    }



    /**
     * 获取window 本地HostName
     * 
     * @return
     * @throws UnknownHostException
     */
    public static String getWinHostName() throws UnknownHostException {
        InetAddress inet = InetAddress.getLocalHost();
        return inet.getHostName();
    }

    public static String getSystemHostName() {
        String hostName = "";
        String osname = IpHelperUtil.getSystemOSName();
        if (isLinux(osname)) { // 针对linux系统
            hostName = SERVER_ENV.get("HOSTNAME");
        } else if (isWindows(osname)) { // 针对Windows系统
            hostName = SERVER_ENV.get("USERDOMAIN");
        } else if (isMac(osname)) { // 针对Mac系统
            hostName = SERVER_ENV.get("LOGNAME");
        }
        logger.info("获取到的系统HostName[{}]", hostName);
        return hostName;
    }





    /**
     * "em%s","en%s", "eno%s", "enp%s","eth%s", "ens%s", "docker%s", "lo%s", "p8p%s", "wlp1s%s"
     * @param cardName
     * @return 
     */
    private static boolean isCardUseful(String cardName) {
        // cardName = "enp26s0f0";
        logger.info("要获取ip的cardName:{}", cardName);
        // System.out.println("要获取ip的cardName:"+cardName);
        for (String cardNameHead : cardNameHeads) {
            logger.info("正在进行匹配的cardNameHead:{}", cardNameHead);
            if (Pattern.matches(String.format(cardNameHead, "\\d*\\S*"), cardName)) {
                return true;
            }
            // if (cardName.indexOf(cardNameHead) != -1) {
            // return true;
            // }
        }
        return false;
    }

    public static boolean isboolIP(String ipAddress) {
        String ip = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
        // ^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    private static String toMacString(byte[] bys) {
        // ^([0-9A-F]{2})(-[0-9A-F]{2}){5}$--MAC正则表达式
        if (bys == null) {
            return null;
        }
        char[] chs = new char[bys.length * 3 - 1];
        for (int i = 0, k = 0; i < bys.length; i++) {
            if (i > 0) {
                chs[k++] = '-';
            }
            chs[k++] = HEX[(bys[i] >> 4) & 0xf];
            chs[k++] = HEX[bys[i] & 0xf];
        }
        String mac = new String(chs);
        return mac;
    }



    /**
     * 
     * 获取当前运行程序的内存信息
     * 
     * @return
     */
    public static final String getRAMinfo() {
        Runtime rt = Runtime.getRuntime();

        return "RAM: " + rt.maxMemory() + " bytes max, " + rt.totalMemory() + " bytes total, " + rt.freeMemory()
                + " bytes free.";
    }


}
